<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useAppStore } from '@/store/modules/app';
import { useAuthStore } from '@/store/modules/auth';

const appStore = useAppStore();
const authStore = useAuthStore();

// 响应式状态
const iframeRef = ref<HTMLIFrameElement>();
const windowSize = ref({
  width: document.body.clientWidth,
  height: document.body.clientHeight
});

// 计算属性：是否显示H5Router
const isVisible = computed(() => {
  return appStore.h5RouterVisible;
});

// 计算实际URL - 完全按照原组件逻辑
const thisUrl = computed(() => {
  const navUrl = appStore.themeConfig.navUrl;
  if (!navUrl) return '';

  const user = authStore.userInfo;
  const userId = (user as any)?.objectId || user?.userId;

  console.log('H5Router URL构建 (原组件逻辑):', {
    navUrl,
    user,
    userId
  });

  if (!userId) {
    console.warn('H5Router: 未找到用户ID');
    return '';
  }

  const baseUrl = import.meta.env.VITE_H5_BASE_URL || 'https://web.jimuzhou.top';
  // 🔧 完全按照原组件：直接字符串拼接，不转义
  const fullUrl = `${baseUrl}/pages/commonNew/h5Router?uid=${userId}&url=${navUrl}`;

  console.log('H5Router最终URL (原组件逻辑):', fullUrl);
  return fullUrl;
});

// 响应式尺寸计算 - 按照原组件逻辑
const containerStyle = computed(() => {
  const { width, height } = windowSize.value;

  // 原组件的尺寸计算逻辑
  const containerWidth = Math.min(width * 0.24, 1200); // 原组件是24%
  const containerHeight = Math.min(height * 0.98, 800); // 原组件是98%

  return {
    width: `${containerWidth}px`,
    height: `${containerHeight}px`
  };
});

const iframeStyle = computed(() => {
  const container = containerStyle.value;
  return {
    width: container.width,
    height: `calc(${container.height} - 60px)` // 减去头部高度
  };
});

// 事件处理 - 按照原组件逻辑
const handleClose = () => {
  appStore.closeH5Router();

  // 触发close事件，传递isAddSuccess状态
  const hasChanges = appStore.themeConfig.isAddSuccess;
  console.log('H5Router关闭，操作成功:', hasChanges);

  // 调用全局回调
  const callbacks = (window as any).__h5RouterCallbacks;
  if (callbacks?.onClose) {
    callbacks.onClose(hasChanges);
  }

  // 清理回调函数
  (window as any).__h5RouterCallbacks = {};
};

const handleMaskClick = () => {
  handleClose();
};

// 窗口尺寸监听 - 按照原组件逻辑
const setWindow = (width = document.body.clientWidth, height = document.body.clientHeight) => {
  windowSize.value = { width, height };
};

const handleResize = () => {
  setWindow();
};

// 监听iframe消息 - 按照原组件逻辑
const handleMessage = (event: MessageEvent) => {
  // 安全检查：验证消息来源
  const allowedOrigins = ['https://web.jimuzhou.top', 'http://localhost:8080'];

  if (!allowedOrigins.includes(event.origin)) {
    return;
  }

  const { data } = event;
  console.log('H5Router收到消息:', data);

  // 按照原组件逻辑处理成功消息
  if (data === 'editSuccess' || data === 'saveSuccess' || data === 'addSuccess') {
    appStore.setH5RouterSuccess();

    // 调用全局回调
    const callbacks = (window as any).__h5RouterCallbacks;
    if (callbacks?.onSuccess) {
      callbacks.onSuccess(data);
    }

    console.log('H5Router操作成功:', data);
  }
};

// 生命周期
onMounted(() => {
  setWindow();
  window.addEventListener('resize', handleResize);
  window.addEventListener('message', handleMessage);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  window.removeEventListener('message', handleMessage);
});
</script>

<template>
  <Teleport to="body">
    <div v-if="isVisible" class="uni-mask" @click="handleClose">
      <div class="modal-container" :style="containerStyle" @click.stop>
        <iframe ref="iframeRef" :src="thisUrl" class="iframClass" :style="iframeStyle" />
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
/* 完全按照原组件的样式 */
.uni-mask {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  top: 0;
  position: fixed;
  left: 0;
  z-index: 999999;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: fadeIn 0.3s ease-out;
  backdrop-filter: blur(4px);
}

.modal-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  overflow: hidden;
  animation: slideIn 0.3s ease-out;
  display: flex;
  flex-direction: column;
}

.iframClass {
  border: none;
  width: 100%;
  flex: 1;
  background: white;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-container {
    margin: 20px;
    max-width: calc(100vw - 40px);
    max-height: calc(100vh - 40px);
    border-radius: 8px;
  }
}

@media (max-width: 480px) {
  .modal-container {
    margin: 10px;
    max-width: calc(100vw - 20px);
    max-height: calc(100vh - 20px);
    border-radius: 6px;
  }
}
</style>
